<route lang="json5">
{
	style: {
		navigationBarTitleText: '7号助手',
		navigationStyle: 'custom',
	},
}
</route>
<template>
	<view class="page bg-white" :style="{ marginTop: safeAreaInsets?.top + 'px' }">
		<text class="login-title">登录</text>

		<wd-form ref="form" custom-class="form" :model="model">
			<wd-cell-group :border="true">
				<wd-input
					label="账号"
					label-width="150rpx"
					prop="username"
					clearable
					v-model="model.username"
					placeholder="请输入账号"
					:rules="[
						{
							required: true,
							message: '请输入账号',
						},
					]"
				/>
				<wd-input
					label="密码"
					label-width="150rpx"
					prop="password"
					type="password"
					clearable
					v-model="model.password"
					placeholder="请输入密码"
					:rules="[
						{
							required: true,
							message: '请输入密码',
						},
					]"
				/>
			</wd-cell-group>

			<view class="footer">
				<wd-button type="primary" size="large" custom-class="login-btn" @click="handleSubmit" block>
					登录
				</wd-button>
			</view>
			<!-- #ifdef H5 -->
			<view class="bottom-side-otherLogin" @click="getWeChatCode" v-if="isWeixin">
				<text>其他社交账号登录</text>
				<image src="https://xuezhifu-resource.oss-cn-hangzhou.aliyuncs.com/newxuefu/mwx/wx.png"></image>
			</view>
			<!-- #endif -->
		</wd-form>

		<!-- #ifdef MP-WEIXIN -->
		<view class="bottom-side-otherLogin" @click="mpGetWeChatCode">
			<text>其他社交账号登录</text>
			<image src="https://xuezhifu-resource.oss-cn-hangzhou.aliyuncs.com/newxuefu/mwx/wx.png"></image>
		</view>
		<!-- 微信获取头像昵称 -->
		<wd-popup v-model="show" position="bottom" custom-style="padding: 30rpx 40rpx; height:600rpx">
			<wd-form>
				<wd-button type="text" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">获取头像</wd-button>

				<view class="lines">
					<wd-img v-if="avatarUrlValue" :src="avatarUrlValue" :width="50" :height="50"></wd-img>
				</view>

				<view class="lines">
					<input
						type="nickname"
						placeholder="获取昵称"
						v-model="nickNameValue"
						@change="handleNicknameChange"
					/>
				</view>

				<wd-button type="primary" @click="handleMpSubmit">授权头像昵称</wd-button>
			</wd-form>
		</wd-popup>
		<!-- #endif -->
	</view>
</template>
<script setup>
import { http } from '@/utils/http'
import { tabBar } from '@/pages.json'

defineOptions({
	name: 'Login',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const form = ref(null)

const isWeixin = ref(false)

const toUrl = (url) => {
	uni.navigateTo({
		url,
	})
}

const model = ref({
	username: '',
	password: '',
})

const avatarUrlValue = ref('')
const nickNameValue = ref('')
const openid = ref('')

const onChooseAvatar = (e) => {
	avatarUrlValue.value = e.avatarUrl
}
const handleNicknameChange = (e) => {
	console.log('e', e)
	nickNameValue.value = e.detail.value
}

const handleMpSubmit = async () => {
	if (avatarUrlValue.value && nickNameValue.value) {
		let res = await http({
			url: '/Usersd/wxMinReg',
			method: 'post',
			data: {
				openid: openid.value,
				nickname: nickNameValue.value,
				avatar: avatarUrlValue.value,
			},
		})
		if (res.code == 200) {
			console.log('res', res)
			uni.showToast({
				title: '登录成功',
				duration: 2000,
				icon: 'none',
			})

			uni.setStorageSync('token', openid.value)

			setTimeout(() => {
				back()
			}, 1500)
		}
	} else {
		uni.showToast({
			title: '请先获取头像昵称',
			duration: 2000,
			icon: 'none',
		})
	}
}

/**
 * 提交
 */
const handleSubmit = async () => {
	form.value
		.validate()
		.then(async ({ valid, errors }) => {
			if (valid) {
				let res = await http.post('/Usersd/pwdLogin', {
					username: model.value.username,
					password: model.value.password,
				})

				if (res.code == 200) {
					uni.showToast({
						title: '登陆成功',
						icon: 'none',
						mask: true,
					})

					uni.setStorageSync('token', res.result.openid)

					setTimeout(() => {
						back()
					}, 1500)
				}
			}
		})
		.catch((error) => {})
}

/*微信登录相关  start*/
//方法：用来判断是否是微信内置的浏览器
const isWechat = () => {
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === 'micromessenger'
}
//方法:用来提取code
const getUrlCode = (name) => {
	return (
		decodeURIComponent(
			(new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(
				/\+/g,
				'%20',
			),
		) || null
	)
}
//检查浏览器地址栏中微信接口返回的code
const checkWeChatCode = () => {
	let code = getUrlCode('code')
	if (code) {
		getOpenidAndUserinfo(code)
	}
}

const show = ref(false)
const code = ref('')

const mpGetWeChatCode = async () => {
	uni.login({
		provider: 'weixin',
		success: async (res) => {
			console.log('res', res)
			code.value = res.code
			// show.value = true

			let resp = await http({
				method: 'post',
				url: '/Usersd/wxMinLogin',
				data: { code: code.value },
			})
			console.log('resp', resp)
			if (resp.code == 200) {
				// 设置用户信息

				// 保存token
				uni.setStorageSync('token', resp.result.openid)
				// 提示用户登录成功
				uni.showToast({
					title: '登陆成功',
					icon: 'none',
					mask: true,
					duration: 1500,
				})
				back()
			} else if (resp.code == 105) {
				uni.setStorageSync('token', resp.result.openid)
				openid.value = resp.result.openid
				uni.navigateTo({ url: '/pages/login/wxRegister?openid=' + openid.value })
			}
		},
		fail: (fail) => {
			console.log('fail', fail)
		},
	})
}

const back = () => {
	let backRoute = uni.getStorageSync('backRoute')
	console.log('%c [ backRoute ]-248', 'font-size:13px; background:pink; color:#bf2c9f;', backRoute)

	if (!backRoute) {
		uni.switchTab({ url: '/pages/index/index' })
	}

	if (backRoute == '/pages/login/index') {
		uni.switchTab({ url: '/pages/index/index' })
	}

	if (backRoute == '/pages/index/index' || backRoute == '/pages/mine/index') {
		uni.switchTab({ url: backRoute })
	} else {
		uni.redirectTo({
			url: backRoute,
		})
	}
}

//请求微信接口，用来获取code
const getWeChatCode = () => {
	let local = encodeURIComponent(window.location.href) //获取当前页面地址作为回调地址
	let appid = 'wx06eec0bfc2ec3c9e'

	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	window.location.href =
		'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
		appid +
		'&redirect_uri=' +
		local +
		'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
}
//把code传递给后台接口，静默登录
const getOpenidAndUserinfo = async (code) => {
	let href = 'https://9hao.jiucun.club/Usersd/wxLogin?code=' + code
	window.location.href = href
}

onMounted(() => {
	// #ifdef H5
	isWeixin.value = isWechat()
	if (isWeixin.value) {
		checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	}
	// #endif
})
</script>
<style lang="scss" scoped>
:deep(.wd-cell-group) {
	background-color: transparent;
}

:deep(.wd-cell-group__body) {
	background-color: transparent;
}

:deep(.wd-input) {
	border-radius: 44rpx;
	margin-bottom: 20rpx;
}

.page {
	background-image: url('http://cdn.gtfy.net.cn/swiper/newMyBg.png');
	background-size: cover;
}

.lines {
	width: 100%;
	height: 120rpx;
	line-height: 120rpx;

	display: flex;
	flex-flow: row nowrap;
	justify-content: flex-start;
	align-items: center;
	gap: 24rpx;

	font-size: 28rpx;
	color: #333;
}

.login-title {
	width: 710rpx;
	line-height: 200rpx;
	text-align: left;
	font-size: 60rpx;
	font-weight: 800;
	color: #fff;
	text-shadow: 0 0 10rpx #333;
}

.form {
	width: 710rpx;
	min-height: 600rpx;
	display: flex;
	flex-flow: column nowrap;
	justify-content: space-between;

	.register {
		width: 100%;

		display: flex;
		justify-content: center;
		align-items: center;

		text-align: center;
	}
}

.footer {
	box-sizing: border-box;
	padding-top: 50rpx;

	display: flex;
	flex-flow: column nowrap;
	align-items: center;
	justify-content: flex-start;

	flex: 1;

	width: 100%;
	height: 100rpx;

	.login-btn {
		width: 300rpx;
		background-image: url(http://cdn.gtfy.net.cn/swiper/newMyBg.png);
		background-color: transparent;
		background-size: cover;
		color: #5a88f1;
	}
}

:deep(.footer) {
	box-sizing: border-box;
	padding-top: 50rpx;

	display: flex;
	flex-flow: column nowrap;
	align-items: center;
	justify-content: flex-start;

	flex: 1;

	width: 100%;
	height: 100rpx;

	.login-btn {
		width: 300rpx;
		background-image: url(http://cdn.gtfy.net.cn/swiper/newMyBg.png);
		background-color: transparent;
		background-size: cover;
		color: #5a88f1;
	}
}

:deep(.form) {
	width: 710rpx;
	min-height: 600rpx;
	display: flex;
	flex-flow: column nowrap;
	justify-content: space-between;

	.register {
		width: 100%;

		display: flex;
		justify-content: center;
		align-items: center;

		text-align: center;
	}
}

.bottom-side-otherLogin {
	width: 100%;

	display: flex;
	flex-flow: column nowrap;
	justify-content: space-between;
	align-items: center;

	gap: 24rpx;
	/* #ifdef MP-WEIXIN */
	color: #4d80f0;
	/* #endif */

	/* #ifdef H5 */
	color: #fff;
	/* #endif */
	font-size: 24rpx;

	image {
		width: 50rpx;
		height: 50rpx;
	}
}
</style>
